//
//  ViewController.swift
//  syrj_project_download
//
//  Created by 张伟 on 2020/10/22.
//  Copyright © 2020 -. All rights reserved.
//

import UIKit
import Alamofire
import HandyJSON
import Kingfisher

let requestUrl = "https://gitee.com/wfn53400/zcqAppDownloadConfig/raw/master/syrj.json"

class ViewController: UIViewController {

    var dataSource : [DataModel] = []
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }

    private func configUI() {
        self.title = "红康云iOS项目下载"
        tableView.register(UINib.init(nibName: "DownloadCell", bundle: nil), forCellReuseIdentifier: "DownloadCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        requestData()
    }

    private func requestData() {
        Alamofire.request(requestUrl).responseJSON { (res) in
            guard let json = res.result.value as? [String:Any] else {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                    self.requestData()
                }
                return
            }
            let data = json["data"] as! [[String:Any]]
            for i in data {
                let model = DataModel.deserialize(from: i)
                self.dataSource.append(model!)
            }
            self.tableView.reloadData()
        }
    }
    
    /// 打开外链
    ///
    /// - Parameter url: 下载地址
    private func openUrlAction(downloadUrl urlString : String) {
        guard let url = URL(string: urlString) else {return}
        let app = UIApplication.shared
        if app.canOpenURL(url) {
            if #available(iOS 10.0, *) {
                app.open(url, options: [:], completionHandler: nil)
            } else {
                app.openURL(url)
            }
        }
    }
    
}

extension ViewController:UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "DownloadCell") as! DownloadCell
        let model = dataSource[indexPath.row];
        cell.title.text = model.title
        cell.icon.kf.setImage(with: URL(string: model.iconUrl))
        return cell
    }
}

extension ViewController:UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let url = dataSource[indexPath.row].downLoadUrl
        openUrlAction(downloadUrl: url)
    }
}



class DataModel: HandyJSON {
    var title  = ""
    var downLoadUrl  = ""
    var iconUrl = ""
    required init() {}
}
